<template>
  <transition name="toast-fade">
    <div v-show="visible" class="toast" :style="{ zIndex: zIndex }">
      <div class="toast_content" :class="[`toast_type_${type}`]">
        <div class="toast_content_text">{{ message }}</div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'Toast',
  data() {
    return {
      visible: false,
      message: '',
      type: 'info',
      duration: 3000,
      zIndex: 9999,
      timer: null,
    };
  },
  methods: {
    show(options) {
      // ✅ 清除上一次的定时器
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }

      // ✅ 先设置数据
      this.message = options.message || '提示';
      this.type = options.type || 'info';
      this.duration = options.duration || 3000;

      // ✅ 强制：先设置 visible = false，再 nextTick 设置 true（确保触发重新显示）
      this.visible = false;

      this.$nextTick(() => {
        this.visible = true;

        // ✅ 设置自动关闭
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            this.hide();
          }, this.duration);
        }
      });
    },
    hide() {
      this.visible = false;
      // 清理定时器
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
  },
};
</script>
<style scoped>
.toast {
  position: fixed;
  top: 10%;
  left: 50%;
  transform: translate(-50%, 0);
  pointer-events: none;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 40px;
  z-index: 9999;
}

.toast_content {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.8);
  text-align: center;
  min-height: 40px;
  display: flex;
  align-items: center;
}

/* 类型样式 */
.toast_type_success {
  background-color: rgba(46, 183, 89, 0.9);
}

.toast_type_error {
  background-color: rgba(245, 83, 83, 0.9);
}

.toast_type_warning {
  background-color: rgba(255, 165, 0, 0.9);
}

.toast_type_info {
  background-color: rgba(0, 0, 0, 0.8);
}

/* 动画 */
.toast-fade-enter-active {
  animation: toast-fade-in 0.3s ease-out;
}

.toast-fade-leave-active {
  animation: toast-fade-out 0.3s ease-in;
}

@keyframes toast-fade-in {
  from {
    opacity: 0;
    transform: translate(-50%, 0);
  }

  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

@keyframes toast-fade-out {
  from {
    opacity: 1;
    transform: translate(-50%, 0);
  }

  to {
    opacity: 0;
    transform: translate(-50%, 0);
  }
}
</style>
